package net.flowas.genericcrud.rest;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Provider
public class ExceptionPriter implements javax.ws.rs.ext.ExceptionMapper {
  private static final Logger LOG = LoggerFactory.getLogger(ExceptionPriter.class);
  
  @Override
  public Response toResponse(Throwable exception) {
    LOG.warn("failed to process bussiness: ", exception);
    Response response;
    if (exception instanceof ConstraintViolationException) {
      response = Response.status(Response.Status.BAD_REQUEST).entity(createViolationResponse(
          ((ConstraintViolationException) exception).getConstraintViolations())).build();
    } else {
      Map<String, String> error = new HashMap<>();
      error.put("propertyPath", "error");
      error.put("message", exception.getMessage());
      response = Response.status(Response.Status.BAD_REQUEST).entity(error).build();
    }
    return response;
  }

  private JsonArray createViolationResponse(Set<ConstraintViolation<?>> violations) {
    JsonArrayBuilder values = Json.createArrayBuilder();
    for (ConstraintViolation<?> violation : violations) {
      values.add(Json.createObjectBuilder().add(violation.getPropertyPath().toString(),
          violation.getMessage()));
    }
    return values.build();
  }
}
